package com.cm386.final_project_timezonealert.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.R;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class AlertTimeService extends Service {
	public final static String TIME_KEY      		 = "TIME";
	public final static String NOIFICATION_TITLE_KEY = "NOIFICATION_TITLE";
	NotificationManager mNotificationManager 		 = null;
	Timer timer1 							 		 = null;
	String notificationTitle						 = "";
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v("Time Service", "Creating...");
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// TODO Auto-generated method stub
		Log.v("Time Service", "Creating...");
		Bundle bData = intent.getExtras();
		String timeString 	  = bData.getString(TIME_KEY);
		notificationTitle = bData.getString(NOIFICATION_TITLE_KEY);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date time;
		try {
			time = format.parse(timeString);
		
			timer1 = new Timer("Timer Service");
			Log.v("SERVICE COUNTER", "Time:" + time);
			
			timer1.schedule(new TimerTask(){
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					sendNotice();
				}} 
			, time);	
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  START_CONTINUATION_MASK;
	}
	
	public void onDestroy() {
		super.onDestroy();
		timer1.cancel();
		
	}
	
	private void sendNotice(){
		Notification notification = new Notification.Builder(this).setContentTitle(notificationTitle).setContentText(notificationTitle)
				.setSmallIcon(R.drawable.ic_popup_reminder)
				.build();
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(1, notification);
	}
}
